var fetch = require('isomorphic-fetch');
import {fetchBegin, fetchSuccess, fetchFail} from './redux/action'

const WEB_BASE = "http://127.0.0.1:3008";

const Api = {};

const getUrl = (interface_)=>(WEB_BASE + interface_);

var uid = 180;

Api.getUserInfo = function (action) {
    return fetchData(getUrl(`/user/${uid}`), action);
};

Api.getDriveCardInfo = function (action) {
    return fetchData(getUrl(`/driveCard/${uid}`), action);
};

// fetch from web
const fetchData = function (url, action, cookie = {}) {
    return function (dispatch) {
        dispatch(fetchBegin(url));
        return fetch(url, cookie)
            .then(response=> response.json())
            .then(json => {
                dispatch(fetchSuccess(url));
                dispatch(action(json.data));
            })
            .catch(err=> {
                console.log(err);
                dispatch(fetchFail(url))
            });
    };
};

module.exports = Api;